#!/usr/bin/env python
#coding=utf-8
import cv2 
import rospy
from cv_bridge import CvBridge
from sensor_msgs.msg import Image
from std_msgs.msg import String
import pyzbar.pyzbar as pyzbar

rospy.init_node('qrcode', anonymous=False)
spub=rospy.Publisher("/qrcode_data",String,queue_size=1)
qrdata=String()
cvb=CvBridge()

def callback(data):
    # print(data)
    frame=cvb.imgmsg_to_cv2(data,desired_encoding="passthrough")
    # 图像灰化，降低计算复杂度
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)   
    barcodes = pyzbar.decode(frame_gray) 
    #将图片传给Zbar
    for barcode in barcodes:
        barcodeData = barcode.data.decode("utf-8")
        if len(barcodeData) >= 1:
            qrdata=barcodeData
            print(qrdata)
            spub.publish(qrdata)
def get_img():
    rospy.Subscriber("camera/rgb/image_raw", Image, callback)
    rospy.spin()

if __name__ == '__main__':
    print("二维码识别启动")
    try:
        get_img()
    except rospy.ROSInterruptException:
        rospy.loginfo("qrcode node terminated.")

